<template>
  <div class="login-page">
    <el-form ref="loginForm" class="el-form" :rules="rule" :model="user">
      <div class="form-label">
        <h1>请登录</h1>
      </div>
      <el-form-item label="账号" prop="username">
        <el-input v-model="user.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="user.password" show-password></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="kaptcha">
        <el-input v-model="user.kaptcha" style="width: 150px; margin-right: 10px;" @keyup.enter="submitHandler"/>
        <img ref="kaptcha" @click="getKaptcha" alt="验证码" src="" height="30" />
      </el-form-item>
      <el-form-item style="display: flex;">
        <el-button type="primary" style="width: 100%" @click="submitHandler">登录</el-button>
      </el-form-item>
      <div class="login-addition">
        <el-button link @click="toChangePassword">忘记密码</el-button>
        <el-button @click="toRegister">注册</el-button>
      </div>
    </el-form>
  </div>

</template>

<script>
import { ref } from 'vue'
import router from '@/router'
import { getKaptchaRequest } from '@/api/kaptcha'
import { mapActions } from 'vuex'

export default {
  name: 'UserLogin',
  setup () {
    return {
      user: ref({
        username: '',
        password: '',
        kaptcha: ''
      }),
      rule: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        kaptcha: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    ...mapActions(['login']),
    submitHandler () {
      this.$refs.loginForm.validate((val) => {
        if (val === true) {
          this.login(this.user)
        }
      })
    },
    toRegister () {
      router.push('/register')
    },
    getKaptcha () {
      getKaptchaRequest().then(val => {
        this.$refs.kaptcha.src = `data:image/png;base64,${val.data}`
      })
    },
    toChangePassword () {
      router.push('/password')
    }
  },
  mounted () {
    this.getKaptcha()
  }
}
</script>

<style scoped>
.login-page{
  width: 600px;
  margin: auto;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 600px;
  background-color: #e3eeef;
}
.form-label{
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 30px 30px;
  padding-top: 0;
}
.login-addition{
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-between;
}
.el-form{
  width: 300px;
}
</style>
